import { createChunk, getChunkCount } from "@/utils/file/chunkUtils";

/**
 * 创建分片线程
 *
 * @param {Object} e.data
 * @param {Number} e.data.threadIndex 线程索引
 * @param {Number} e.data.threadCount 线程数量
 * @param {File} e.data.file 文件
 * @returns {Array} 分片结果
 */
onmessage = (e) => {
  let { threadIndex, threadCount, file } = e.data;
  const chunkCount = getChunkCount(file);

  const workerChunkCount = Math.ceil(chunkCount / threadCount); // 处理分片数量

  const startIndex = threadIndex * workerChunkCount;
  let endIndex = startIndex + workerChunkCount;
  if (endIndex > chunkCount) {
    endIndex = chunkCount;
  }

  const result = [];
  for (let index = startIndex; index < endIndex; index++) {
    result.push(createChunk(file, index));
  }

  Promise.all(result).then((res) => postMessage(res));
};
